﻿using System;
using System.Collections.Generic;
using System.Text;
using MVCFoto.IDAL;
using MVCFoto.Model;
using System.Data.SqlClient;
using System.Data;

namespace MVCFoto.SQLServerDAL
{
    public class Tag:ITag
    {
        public TagInfo GetTag(string name)
        { 
            SqlParameter[] param = {
			            SqlHelper.MakeInParam("@Name",SqlDbType.VarChar,50,name)			          
	            };
            TagInfo tag = null;
            using (SqlDataReader sdr = SqlHelper.ExecuteReader("mfp_Get_Tag", param))
            {
                while (sdr.Read())
                {
                    tag = new TagInfo();
                    tag.TagID = sdr.GetInt32(0);
                    tag.Name = sdr.GetString(1);
                    tag.Reference = sdr.IsDBNull(2) ? 0 : sdr.GetInt32(2);
                }
            }
            return tag;
            
        }

        public int AddTag(string name)
        {
            SqlParameter[] param = {
			            SqlHelper.MakeInParam("@Name",SqlDbType.VarChar,50,name)			          
	            };
            return (int)SqlHelper.ExecuteOneValue("mfp_Insert_Tag", param);
            
        }

        public bool AddPhotoTag(int photoId, int tagId)
        { 
            

                SqlParameter[] param = {
                        SqlHelper.MakeInParam("@PhotoID",SqlDbType.Int,4,photoId),
			            SqlHelper.MakeInParam("@TagID",SqlDbType.Int,4,tagId)			          
	            };
                return SqlHelper.ExecuteNonQuery("mfp_Insert_PhotoTag", param) > 0 ? true : false;
        }

        public bool DeletePhotoTag(int photoId, int tagId)
        {
            SqlParameter[] param = {
                        SqlHelper.MakeInParam("@PhotoID",SqlDbType.Int,4,photoId),
			            SqlHelper.MakeInParam("@TagID",SqlDbType.Int,4,tagId)			          
	            };
            return SqlHelper.ExecuteNonQuery("mfp_Delete_PhotoTag", param) > 0 ? true : false;
        }

        public IList<TagInfo> GetPhotoTags(int photoId)
        {
            //

            SqlParameter[] param = {
			            SqlHelper.MakeInParam("@PhotoID",SqlDbType.Int,4,photoId)			          
	            };
            IList<TagInfo> tags = new List<TagInfo>();
            using (SqlDataReader sdr = SqlHelper.ExecuteReader("mfp_Get_Photo_Tags", param))
            {
                while (sdr.Read())
                {
                    TagInfo tag = new TagInfo();
                    
                    tag.TagID = sdr.GetInt32(0);
                    tag.Name = sdr.GetString(1);
                    tag.Reference = sdr.IsDBNull(2) ? 0 : sdr.GetInt32(2);
                    tags.Add(tag);
                }
            }
            return tags;
        }
    }
}
